package com.xc.smart.interceptor;



import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.xc.smart.annotation.Login;
import com.xc.smart.exception.RRException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 权限传参判断(Token)验证
 * @author Admin
 */
@Configuration
@Component
public class AuthorizationInterceptor extends HandlerInterceptorAdapter {


    public static final String TOKEN_NAME = "Authorization";

    public static final String TOKEN_HEADER = "tk:";

    /**
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Primary
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Login annotation;
        if(handler instanceof HandlerMethod) {
            annotation = ((HandlerMethod) handler).getMethodAnnotation(Login.class);
        }else{
            return true;
        }
        if(annotation == null){
            return true;
        }
        //从header中获取token
        String token = request.getHeader(TOKEN_NAME);
        //如果header中不存在token，则从参数中获取token
        if(StringUtils.isBlank(token)){
            token = request.getParameter(TOKEN_NAME);
        }
        //token为空
        if(StringUtils.isBlank(token)){
            throw new RRException("请先登录",201);
        }

        return true;
    }
}
